<template>
  <el-select
      v-model="selectedValue"
      :placeholder="placeholder"
      :loading="loading"
      @change="updateValue"
      @keyup.enter.native="keyEntry"
      filterable
      :clearable="true"
      :default-first-option = "false"
      :dropdown-append-to-body="false"
      ref="modelRef"
  >
    <!--    :reserve-keyword ="false"-->
    <el-option
        v-for="item in options"
        :key="item[fieldMappings.key]"
        :label="item[fieldMappings.label]"
        :value="item[fieldMappings.value]"
    />
  </el-select>
</template>

<script setup lang="ts">
import {nextTick, onMounted, ref, watch} from 'vue';
import { ElSelect, ElOption } from 'element-plus';

defineOptions({
  name: 'RemoteSearchSelect'
});

const props = defineProps({
  modelValue: [String, Number],
  placeholder: String,
  data: {} as any,
  fetchOptions: {
    type: Function,
    required: true
  },
  api: {
    type: Function,
    default: (query: any) => query
  },
  fieldMappings: {
    type: Object,
    default: () => ({
      key: 'id',
      label: 'label',
      value: 'value'
    })
  },
});

let newSrcUrl = ref('')

const emits = defineEmits(['update:modelValue','modelEntry','fatherMothed']);

const selectedValue = ref(props.modelValue);
const loading = ref(false);
const options = ref<any[]>([]);
let modelRef = ref()

const initList = async () => {
    loading.value = true;
    try {
      const queryParams = props.api('null');
      const result = await props.fetchOptions(queryParams);
      options.value = result.data;
    } catch (error) {
      console.error('Error fetching options:', error);
    } finally {
      loading.value = false;
    }
};

initList()

//生命周期问题需要这样操作
onMounted(() => {
  nextTick(() => {
    console.log('modelRef.value',modelRef.value)
    if (modelRef.value) {
      modelRef.value.focus();  // 聚焦 el-select
    }
  });
});


const updateValue = (value: any) => {
  if (props.data){
    const selectedOption = options.value.find(option => option.id === value);
    emits('update:modelValue',
        value,
        newSrcUrl.value!=''?newSrcUrl.value: props.data,
        selectedOption);
    selectedValue.value = ''
    modelRef.value.focus()
    return
  }
  emits('update:modelValue', value,newSrcUrl.value!=''?newSrcUrl.value: props.data);
};


const keyEntry = (event: any) => {
  console.log('士大夫撒大范围防守打法11',event.target.nextSibling)
  console.log('士大夫撒大范围防守打法',event.target.nextSibling.textContent)
  if (event.target.nextSibling.textContent === ''){
    return
  }
  emits('modelEntry'
      ,event.target.nextSibling.textContent,
      newSrcUrl.value!='' ?newSrcUrl.value: props.data);
  emits('fatherMothed',props.data)
  //如何是这样清除掉输入框的？？？
  event.target.nextSibling.click()
  modelRef.value.focus()

};


watch(
    () => props.modelValue,
    newValue => {
      selectedValue.value = newValue;
    }
);

/**
 * 给编辑模式用的，直接修改数据
 */

defineExpose({newSrcUrl})

</script>
